package com.game.view.layer
{
	import com.dusk.game.Logger;
	import com.dusk.util.ResUtil;
	import com.game.event.GameEventType;
	import com.game.manager.EventManager;
	import com.game.manager.GameSceneManager;
	
	import config.Config;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class GameCartoon extends LayerBase
	{
		
		public static const GO_MENU:int = 1;
		public static const FIGHT:int = 2;
		public static const CONTINUE_GAME:int = 3;
		public static const SHOW_MAP:int = 4;
		public static const SHOW_VICTOR:int = 5;
		public static const NONE:int = 6;
		
		public function GameCartoon()
		{
			super();
		}
		
		public static var SHOW_CARTOON_OVER:String = "showCartoonOver";
		public var mc:MovieClip;
		private var aftType:int;
		
		override protected function beforeAdded():void
		{
			mc = ResUtil.getLayerView("GameCartoon") as MovieClip;
			mc.gotoAndStop(1);
			addChild(mc);
		}
		
		public function show(tarScene:String,aftType:int,isRepeat:Boolean = false):void
		{
			this.aftType = aftType;
			if(this.mc != null)
			{
				try{
					mc.gotoAndStop(tarScene);
				}catch (e:Error)
				{
					Logger.logError("找不到帧标签:" + tarScene,this);
				}
			}
			else
			{
				throw new Error("动画内容mc不能为空")
			}
			if(!isRepeat)
			{
				if(Config.getIns().userData.showedCartoon.indexOf(tarScene) != -1)
				{
					this.doShowOver();
					return;
				}
				Config.getIns().userData.showedCartoon.push(tarScene);
			}
			if(!tarScene)
			{
				this.doShowOver();
			}
			GameSceneManager.getIns().addScene(this);
		}
		
		override protected function onAdded():void
		{
			if (!hasEventListener(MouseEvent.CLICK))
			{
				this.addEventListener(MouseEvent.CLICK, this.nextPage);
			}
		}
		
		override protected function onRemoved():void
		{
			if(hasEventListener(MouseEvent.CLICK))
			{
				this.removeEventListener(MouseEvent.CLICK, this.nextPage);
			}
		}
		
		private function nextPage(param1:MouseEvent):void
		{
			var mc:MovieClip = this.mc.getChildAt(0) as MovieClip;
			if(mc == null)
			{
				this.doShowOver();
				return;
			}
			if(mc.currentFrame < mc.totalFrames)
			{
				mc.nextFrame();
			}
			else
			{
				this.doShowOver();
			}
		}
		
		private function doShowOver():void
		{
			switch (this.aftType)
			{
				case GO_MENU:
					GameSceneManager.getIns().switchScene(GameSceneManager.GAME_MENU);
					break;
				case SHOW_MAP:
					GameSceneManager.getIns().switchScene(GameSceneManager.GAME_MAP);
					break;
				case CONTINUE_GAME:
					EventManager.getIns().dispatchEvent(GameEventType.CONTINUE_GAME);
					break;
				case SHOW_VICTOR:
				case FIGHT:
				case NONE:
			}
			this.dispatchEvent(new Event(GameCartoon.SHOW_CARTOON_OVER));
			removeFromParent();
		}
	}
}
